﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;

namespace Server
{
    public partial class ServerGui : Form
    {
        private Server server;
		private AuktionsService auktionsService;
		private Thread serverThread;

        public ServerGui()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            auktionsService = new AuktionsService();
            server = new Server(auktionsService, 1337);
            serverThread = new Thread(server.Run);
            serverThread.Start();
            auktionsService.ClientInfo += updateAuctionMembers;
        }
        /// <summary>
        /// Starts the Auction with the name and minimum price filled in the textboxes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStartAuction_Click(object sender, EventArgs e)
        {
            lbxAuctions.Items.Clear();
            string name = tbxItemName.Text;
            double minimumPrice;
            bool isdouble = double.TryParse(tbxMinimumPrice.Text, out minimumPrice);
            if (isdouble)
            {
                auktionsService.NewAuction(name, minimumPrice);
                IEnumerator<Auction> auctions = auktionsService.GetAuctions();
                while (auctions.MoveNext())
                    lbxAuctions.Items.Add(((Auction)auctions.Current).Name);
            }
            else
                MessageBox.Show("Minimums prisen skal være et tal");

        }
        /// <summary>
        /// Used for updating the member list on the gui to see who is connected.
        /// </summary>
        /// <param name="msg"></param>
        private void updateAuctionMembers(string msg)
        {
            if (InvokeRequired)
            {
                Invoke(new AuktionsService.BroadCastEventHandler(updateAuctionMembers), msg);
            }
            else
            {
                string[] memberString = msg.Split(';');
                if (memberString[0] == "Logon")
                    lbxAuctionMembers.Items.Add(memberString[1]);
                else
                    lbxAuctionMembers.Items.Remove(memberString[1]);
            }
        }
        
        private void ServerGui_FormClosing(object sender, FormClosingEventArgs e)
        {
			if (serverThread.IsAlive)
			{
				this.server.Stop();
				serverThread.Join();
			}
			else
			{
				return;
			}
        }
    }
}
